﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;

namespace KCommon
{
    /// <summary>
    /// 查找窗体类
    /// </summary>
    public class SearchWindow
    {
        /// <summary>
        /// 要查找的窗体名称
        /// </summary>
        private static string WindowTitle;        

        /// <summary>
        ///是否区分大小写
        /// </summary>
        private static bool CaseSensitive = false;

        /// <summary>
        /// 找到的匹配窗体
        /// </summary>
        private static List<IntPtr> ltFindWindows = new List<IntPtr>();

        /// <summary>
        /// 查找
        /// </summary>
        /// <returns></returns>
        public static IntPtr[] Search(string WindowTitle, string FormClassName = "", string MatchType = "模糊", bool CaseSensitive = false)
        {
            SearchWindow.WindowTitle = WindowTitle;
            SearchWindow.CaseSensitive = CaseSensitive;

            //清除上次查找记录            
            ltFindWindows.Clear();

            //1、按类名找
            if (!string.IsNullOrEmpty(FormClassName))
            {
                //按给定的窗体类名查找
                IntPtr ipWindow = WinAPI.FindWindow(FormClassName, WindowTitle);
                if (ipWindow == IntPtr.Zero && !string.IsNullOrEmpty(WindowTitle))
                {
                    ipWindow = WinAPI.FindWindow(FormClassName, "");
                }
                //添加到搜索到的记录集
                if (ipWindow != IntPtr.Zero)
                {
                    ltFindWindows.Add(ipWindow);
                }
            }

            //2、按标题找 
            //从所有窗体中根据标题查找            
            if (ltFindWindows.Count == 0 && !string.IsNullOrEmpty(WindowTitle))
            {
                WinAPI.EnumWindows(new CallBack(Find), MatchType == "精确" ? 1 : 0);
            }
            return ltFindWindows.ToArray();
        }

        /// <summary>
        /// 查找窗体回调函数
        /// </summary>
        /// <param name="hwnd">当前枚举到的窗体句柄</param>
        /// <param name="lParam">0模糊/1精确</param>
        /// <returns></returns>
        private static bool Find(IntPtr hwnd, int lParam)
        {
            try
            {
                StringBuilder sbWindowText = new StringBuilder(100);
                WinAPI.GetWindowText(hwnd, sbWindowText, sbWindowText.Capacity);
                string NowWindowText = CaseSensitive ? sbWindowText.ToString() : sbWindowText.ToString().ToUpper();
                string LookWindowText = CaseSensitive ? WindowTitle : WindowTitle.ToUpper();
                //当前窗体标题与查找的匹配
                if (NowWindowText == LookWindowText
                    || lParam == 0 
                    && NowWindowText.IndexOf(LookWindowText) >= 0)
                {
                    ltFindWindows.Add(hwnd);
                }
                return true;
            }
            catch
            {
                return false;
            }
        }
    }
}
